from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
import os
from server.common.variable import THREAD_LOCAL_DATA

load_dotenv()

from server.agent_chat.agent_chat import AgentChat
from server.common.vo import UserVo

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

agent_chat = AgentChat().create_workflow()
app = FastAPI()



app.add_middleware(
    CORSMiddleware,
    # 允许的源列表，可以使用 ["*"] 表示允许所有源，但不建议在生产环境使用
    allow_origins=["*"],
    # 允许的方法，如 ["GET", "POST", "PUT", "DELETE"]
    allow_methods=["*"],
    # 允许的头信息，如 ["Content-Type", "Authorization"]
    allow_headers=["*"],
    # 允许携带 Cookie 等凭证，通常在需要认证时设置为 True
    allow_credentials=True,
    # 允许的响应头，通常使用 ["*"] 表示允许所有响应头
    expose_headers=["*"],
)


@app.post("/chat")
async def chat(user_vo: UserVo):

    if user_vo.id is None:
        return {"message": "Please provide user id."}
    THREAD_LOCAL_DATA.user_id = user_vo.id

    system_prompt = '''You are a helpful healthcare assistant. You can chat with users, provide medical advice,
                      and manage users' health data by using tools.
                      The information of the user chatting with you currently is as follows:
                      username:{username}, sex:{sex}, location:{location}'''
    template = ChatPromptTemplate([
        ("system", system_prompt),
        ("human", user_vo.query)
    ])
    chain = template | agent_chat
    response = chain.invoke({"username": user_vo.nickname, "sex": user_vo.sex, "location": user_vo.location})
    return {"message": response["messages"][-1].content}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
